package com.anysoft.web;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;

import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.WebViewNetworkProtocol;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.me.base.BaseFundWebViewActivity;
import com.anysoft.me.config.CommentConfig;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.PreferencesUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.OnClick;

/**
 * wyb 2017-04-06
 */
public class MyfundDetailActivity extends BaseFundWebViewActivity {

    private String token = "";
    private String sUrl;
    private String fundcode;
    private String cusNo;
    private String fundname;

    private String shareClass;
    private String fundType;
    private String fundState;
    private String fundstateid;
    private String fundrisklevel;
    private String fundstateDescription;
    private String titleStr;
    private boolean isFirstFundDetail = true; //是否是第一次进入

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (PreferencesUtils.getBoolean(this, CommentConfig.SPFlag.IS_FIRST_FUNDDETAIL)) {
            isFirstFundDetail = false;
        }
        PreferencesUtils.putBoolean(this, CommentConfig.SPFlag.IS_FIRST_FUNDDETAIL, true);
        getIntentValue();
        titleStr = fundname + " " + fundcode;
        rightButton.setVisibility(View.INVISIBLE);
        cmtv_title.setText(titleStr);
        subTitle.setText(fundstateDescription);
        String param1 = String.format("fundCode=%s&cusNo=%s&%s",
                fundcode, cusNo, HttpUtils.getCommonParams2StringByWeb(mActivity));
        loadUrl = generateUrl("myfundDetail", param1 + "&fundstateid=" + fundstateid + "&fundType=" + fundType +
                "&fundName=" + fundname + "&shareClass=" + shareClass + "&fundState=" + fundState + "&fundrisklevel=" + fundrisklevel
                + "&fundstateDescription=" + fundstateDescription + "&isFirstFundDetail=" + isFirstFundDetail);
        if (!TextUtils.isEmpty(fundcode)) {
            queryFundInfo(fundcode);
        }

        if (CommonUtil.isNetWorkConnected(mActivity)) {
            setWebViewConfig(loadUrl);
        }

//        SharePopup.setOnShareEventLinstener(new OnShareEventLinstenerImpl() {
//            @Override
//            public void onShareSuccess() {
//                AnalyticsEventUtils.toShareFundEvent(MyfundDetailActivity.this);
//            }
//        });

    }

    private void getIntentValue() {
        if (getIntent() == null) {
            finish();
        }
        cusNo = getFundCustomerNo();
        fundcode = getIntent().getStringExtra("fundCode");
        fundname = getIntent().getStringExtra("fundName");

        shareClass = getIntent().getStringExtra("shareClass");
        fundType = getIntent().getStringExtra("fundType");
        fundState = getIntent().getStringExtra("fundState");
        fundstateid = getIntent().getStringExtra("fundstateid");
        fundrisklevel = getIntent().getStringExtra("fundrisklevel");
        fundstateDescription = getIntent().getStringExtra("fundstateDescription");
        token = getToken();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!token.equals(getToken())) {
            token = getToken();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {

        String url_decode = null;
        try {
            url_decode = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MentorLogger.Log(TAG, "url_decode=" + url_decode);
        String mainTitle;
        String infoTitle;
        Map<String, String> map = new HashMap<>();
        String[] params = url_decode.split("\\?")[1].split("&");
        for (int i = 0; i < params.length; i++) {
            String key = params[i].split("=")[0];
            String value = "";
            try {
                value = params[i].split("=")[1];
            } catch (Exception exception) {
                MentorLogger.Log(TAG, "value为null");
            }
            map.put(key, value);
        }
        mainTitle = map.get("fundName") + " " + map.get("fundCode");
        infoTitle = map.get("infoTitle");
        Intent mIntent = new Intent();
        if (url.contains("prompt.html")) {
            mIntent.setClass(mActivity, SelectWarmPromptActivity.class);
            mIntent.putExtra("url", url);
            startActivity(mIntent);
        } else if (url.contains("fundHistory.html")) {
            mIntent.setClass(mActivity, FundDetailHistoryActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains("tradingInformation.html")) { //交易信息
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", fundstateDescription);
            mIntent.putExtra("infoTitle", "交易信息");
            mIntent.putExtra("url_title", "tradingInformation");
            startActivity(mIntent);
        } else if (url.contains("earnings.html")) { //更多收益和查看更多
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", fundstateDescription);
            mIntent.putExtra("infoTitle", "");
            mIntent.putExtra("url_title", "earnings");
            startActivity(mIntent);

        } else if (url.contains("fundFile.html")) { //基金档案 和基金经理
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "fundFile");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", fundstateDescription);
            mIntent.putExtra("infoTitle", infoTitle);
            startActivity(mIntent);

        } else if (url.contains("fundScalePortio.html")) { //规模份额 3.0.8新增
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "fundScalePortio");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", fundstateDescription);
            mIntent.putExtra("infoTitle", "规模份额");
            startActivity(mIntent);
        } else if (url.contains("portfolio.html")) { //投资组合 3.0.8 fundDetailInfo 改为portfolio
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", fundstateDescription);
            mIntent.putExtra("infoTitle", "投资组合");
            mIntent.putExtra("url_title", "portfolio");
            startActivity(mIntent);
        } else if (url.contains("sameTypeFund.html")) { //同类型基金
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "sameTypeFund");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", fundstateDescription);
            mIntent.putExtra("infoTitle", "同类型基金");
            startActivity(mIntent);
        } else if (url.contains("fundHistoryShare.html")) { //历史分红  3.0.8新增
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "fundHistoryShare");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", fundstateDescription);
            mIntent.putExtra("infoTitle", "历史分红");
            startActivity(mIntent);
        } else if (url.contains("fundAnnoumentnce.html")) { //基金公告  3.0.8新增
            mIntent.setClass(mActivity, FundDetailCommentActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("url_title", "fundAnnoumentnce");
            mIntent.putExtra("fundName", fundname);
            mIntent.putExtra("fundCode", fundcode);
            mIntent.putExtra("subTitleStr", fundstateDescription);
            mIntent.putExtra("infoTitle", "基金公告");
            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GOTO_LOGIN)) { //登录
            ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
            EventBus.getDefault().post(new TimeOutEvent(true));
        } else if (url.contains(WebViewNetworkProtocol.GOTO_E_CHART)) { //横屏
            mIntent.setClass(mActivity, FundDetailEchartActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GO_QUESTION)) {
            startRiskActivity(null);
        } else {
            webview.loadUrl(url);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }


    @OnClick({R.id.shareButton, R.id.leftButton})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.leftButton:
                finish();
                break;

            case R.id.shareButton:
                //请求查询基金接口获取近一年收益值
                String periodYearOne = getFundPeriodYearOne();

                //TODO 需要H5对应连接地址
//                http://127.0.0.1:8020/GYRX/fundDetailSec.html?fundCode=486001&fundType=8
                String url = HostConstant.HOST_WEB_URL_HEADER + String.format("fundDetailSec.html?fundCode=%s&fundType=%s", fundcode, fundType);
//                SharePopup.Share(mActivity, ""+fundname+fundcode, url, "点击查看基金详情");

//                SharePopup.Share(mActivity, mActivity.getResources().getString(R.string.share_title), url, fundname + " " + fundcode + "\n近一年收益率" + periodYearOne);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
